import Vue from 'vue';
import busHolder from '../vue/bus';

import '../vue/topnav';

let bus = busHolder.getBus;

import('../vue/ants.js').then(() => new Vue({
  el : '#root',
  data : {
    loading : true,
    version : "0.5.0 beta",
    current : -1, // 是 menus 的索引, 告诉大家它选了第几个
    menus : [
      { id : 'danmaku', name : '弹幕连接', icon : 'icon_4.png' },
      { id : 'timer', name : '计时器', icon : 'icon_2.png' },
      { id : 'save', name : '存档管理', icon : 'icon_3.png' },
      { id : 'common', name : '通用配置', icon : 'icon_common.png' },
    ],

    // common
    commonRescanLoading : false,

    // timer
    timer : {
      //
    },

    // save
    save : {
      load : false,
      series : '', // 左边选择的
      search : '', // 搜索框里面输入的
      timeline : [], // 左边竖着的列表
      archives : [],
      showArchiveRecord : false,
      currentArchive : null,
      archiveRecords : [],

      seriesList : [], // 元数据
      archiveColumns : [
        {
          dataIndex: 'version',
          key: 'version',
          title: '版本号',
        },
        {
          dataIndex: 'date',
          key: 'time',
          title: '创建时间',
        },
        {
          key: 'action',
          title: '操作',
          scopedSlots: { customRender: 'action' },
        },
      ]
    },

    // danmaku
    danmaku : {
      load : false,
      showRecords : false,
      records : '',
      data : [],
    },
  },
  methods : {
    btnCommonRescan : function () {
      this.commonRescanLoading = true;
      fetch('/aurora/asset/rescan')
        .then((res) => res.json())
        .then((_data) => {
          if (_data.result == false) {
            throw _data;
          }
          this.$message.success('刷新资源成功了');
          this.commonRescanLoading = false;
        }).catch((e) => {
          this.$message.warning('刷新资源失败了');
          console.error('刷新资源失败', e);
          this.commonRescanLoading = false;
        });
    },

    btnMenu : function (toIndex) {
      this.current = toIndex;
      const to = this.menus[toIndex];
      switch (to.id) {
        case 'danmaku': this.onDanmakuShow(); break;
        case 'save': this.onSaveShow(); break;
      }
    },

    // danmaku
    onDanmakuShow : function () {
      if (this.danmaku.load) {
        return;
      }

      this.loadDanmakuList();
      this.danmaku.load = true;
    },
    loadDanmakuList : function () {
      fetch('/aurora/asset/danmaku/all')
        .then((res) => res.json())
        .then((_data) => {
          if (_data.result == false) {
            throw _data;
          }
          this.danmaku.data = _data.data;
        }).catch((e) => {
          this.$message.warning('弹幕数据刷新失败了');
          console.error('弹幕数据刷新失败了', e);
        });
    },
    btnDanmukuRecord : function (o) {
      this.danmaku.records = '';
      this.danmaku.showRecords = true;
      fetch('/aurora/asset/danmaku/pretty/' + o.id)
        .then((res) => res.text())
        .then((_data) => { this.danmaku.records = _data; });
    },
    btnDanmukuRecordClose : function () {
      this.danmaku.showRecords = false;
    },

    // save
    onSaveShow : function () {
      if (this.save.load) {
        return;
      }

      this.loadSaveSeriesList();
      this.save.load = true;
    },
    loadSaveSeriesList : function () {
      return fetch('/aurora/asset/allSeries')
        .then((res) => res.json())
        .then((_data) => {
          if (_data.result == false) {
            throw _data;
          }
          const list = [];
          for (let k in _data.data) {
            list.push({
              name : k,
              count : 0,
              load : false
            });
          }
          this.save.seriesList = list.sort((a, b) => a.name.localeCompare(b.name));
          this.save.timeline = this.save.seriesList;
        });
    },
    onSaveSearchChange : function () {
      if (this.save.search == '') {
        this.save.timeline = this.save.seriesList;
        return;
      }
      this.save.timeline = this.save.seriesList.filter(s => s.name.includes((this.save.search)));
    },
    onSaveSeriesChange : function (value) {
      this.save.series = value;
      this.save.archives = [];
      fetch('/aurora/asset/save/list/' + value)
        .then((res) => res.json())
        .then((_data) => {
          if (_data.result == false) {
            console.error('查询 ' + value + ' 下的存档失败', _data);
            return;
          }
          this.save.archives = _data.data;
          const items = this.save.seriesList.filter(s => s.name == value);
          if (items.length == 0) {
            return;
          }
          items[0].load = true;
          items[0].count = _data.data.length;
        });
    },
    saveDownloadLink(saveId, version = null) {
      let text = location.origin + '/aurora/asset/save/read/' + saveId;
      if (version == null) {
        return text;
      }
      return text + '?version=' + version;
    },
    btnSaveShowRecord : function (record) {
      this.save.showArchiveRecord = true;
      this.save.currentArchive = record;
      this.save.archiveRecords = [];
      fetch('/aurora/asset/save/find/' + record.id)
        .then((res) => res.json())
        .then((_data) => {
          if (_data.result == false) {
            console.error('查询 ' + record.id + ' 存档详情失败', _data);
            return;
          }
          const list = _data.data.archives;
          for (let i = 0; i < list.length; i++) {
            let date = new Date(list[i].createTime);
            list[i].date = this.dateFormat(date, 'yyyy-MM-dd hh:mm:ss');
          }
          this.save.archiveRecords = list;
        });
    },
    btnSaveRecordClose : function () {
      this.save.showArchiveRecord = false;
    },

    // other
    dateFormat : function (date, fmt) {
      var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
      return fmt;
    }
  },
  mounted : function () {
    bus().$on(busHolder.KEY_TOP_NAV_CLICK, (url) => {
      location.href = url;
    });
  }
}));
